import base64
import pickle

from django.shortcuts import render
from django_redis import get_redis_connection


def merge_cart_cookie_to_redis(request, response):

    cart_str = request.COOKIES.get('carts')
    if cart_str:
        return render(request, 'cart.html')

    # str 转为 dict
    cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))

    user = request.user

    redis_conn = get_redis_connection('carts')

    for sku_id in cart_dict:
        redis_conn.hset('cart_%s' % user.id, sku_id, cart_dict[sku_id]['count'])
        if cart_dict[sku_id]['selected']:
            redis_conn.sadd('selected_%s' % user.id, sku_id)
        else:
            redis_conn.srem('selected_%s' % user.id, sku_id)

    response.delete_cokkie('cart')
